package net.mysoft.budgetsoft.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.mysoft.budgetsoft.system.dao.OrgDao;
import net.mysoft.budgetsoft.system.domain.PageData;
import net.mysoft.budgetsoft.system.domain.TOrg;
import net.mysoft.budgetsoft.system.service.OrgService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

@SuppressWarnings({"rawtypes", "unchecked"})
@Service("orgService")
public class OrgServiceImpl implements OrgService {
	
	@Autowired
	private OrgDao orgDao;

	@Override
	public String getOrgTree() {
		List<TOrg> orgs = orgDao.find("from TOrg");
		List tree = new ArrayList();
		for(TOrg org:orgs) {
			Map map = new HashMap();
			map.put("id", org.getId());
			map.put("text", org.getName());
			TOrg parent = org.getParent();
			map.put("pid", parent==null?null:parent.getId());
			tree.add(map);
		}
		return JSON.toJSONString(tree);
	}

	@Override
	public PageData getOrgByPage(String pid, int pageNow, int pageSize) {
		PageData page = new PageData();
		page.setPageNumber(pageNow);
		page.setPageSize(pageSize);
		String listHql = "select new map(t.id as id, t.name as name, t.orgNo as orgNo, t.type as type) from TOrg t";
		String countHql = "select count(*) from TOrg";
		Map params = new HashMap();
		List paramList = new ArrayList();
		if(StringUtils.isNotBlank(pid)) {
			listHql+=" where t.parent.id = :pid";
			countHql+=" where parent.id = ?";
			params.put("pid", pid);
			paramList.add(pid);
		}
		List<TOrg> orgs = orgDao.queryPageByHql(listHql, params, pageNow, pageSize);
		page.setRows(orgs);
		page.setTotal(orgDao.count(countHql, paramList).intValue());
		return page;
	}

}
